//
//  PlayUIView.m
//  CountDown2
//
//  Created by mmac on 11/9/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PlayUIView.h"
#import "PlayViewController.h"
#import "CountDownProgressView.h"
#import <QuartzCore/QuartzCore.h>


#define CD_COUNT_TOTAL 300
#define CD_COUNT_INTERVAL 0.2
#define CD_COUNT_PUNISH 20

@implementation PlayUIView

@synthesize viewController;




- (void)startTimer {
	
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:CD_COUNT_INTERVAL
													  target:self 
													selector:@selector(cdTimerFireMethod:)
													userInfo:nil
													 repeats:YES];
    cdTimer = timer;
}

- (void)stopTimer {
    [cdTimer invalidate];
    cdTimer = nil;
}

- (void)cdTimerFireMethod:(NSTimer*)theTimer {
	cdCount++;
	[self showCdCount];
}

- (void)showCdCount{
	float pg;
	pg = (float)( cdCountTotal - cdCount ) / (float)(cdCountTotal);
	// NSLog( @"pg %f", pg );
	if(pg < 0.0 || pg > 1.0){
		pg = 0.0;
	}
	countDownProgressView.progress = pg;
	
	if(pg <= 0.0){
		// times up, game over
		NSLog(@"times up, game over");
		[self stopTimer];
		[self prepareGameOver];
	}
	
	// NSLog( @"Count %u, %f", cdCount, pg );
}

- (void)prepareGameOver{
    [NSTimer scheduledTimerWithTimeInterval:2.0
									 target:self
								   selector:@selector(loadGameOver:)
								   userInfo:nil
									repeats:NO];
	_gameOver = TRUE;
	[self setNeedsDisplay];
}

- (void)loadGameOver:(NSTimer*)theTimer{
	[viewController loadGameOver];
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{
	// [gameClearLayer removeFromSuperlayer];
	
	/*
	if(FALSE == flag){
		CGPoint point = CGPointMake(140, 80);
		gameClearLayer.position = point;
	
	
		CGSize size = CGSizeMake(160, 160);
		NSValue *value = [NSValue valueWithCGSize:size];
		[gameClearLayer setValue:value forKeyPath:@"bounds.size"];

	}
	*/
	
}
	
- (void)prepareNextLevel{

	[NSTimer scheduledTimerWithTimeInterval:1.0
									 target:self
								   selector:@selector(loadNextLevel:)
								   userInfo:nil
									repeats:NO];
	_gameClear = TRUE;
	_gameClearAnimation = TRUE;
	
	UIImage *clearImage          = [[UIImage imageNamed: @"clear_animation.jpg"] retain];
		
	gameClearLayer          = [CALayer layer];
	gameClearLayer.anchorPoint  = CGPointMake (0, 0);   
	gameClearLayer.frame        = CGRectMake(160, 80, 160, 160);  
	gameClearLayer.contents     = (UIImage *) clearImage.CGImage;
	[self.layer addSublayer:gameClearLayer ];

	
	/*
	NSNumber *zeroNumber    = [NSNumber numberWithFloat:0.0];
	NSNumber *oneNumber             = [NSNumber numberWithFloat:1.0];

	
	CABasicAnimation *theAnimation=[[CABasicAnimation animationWithKeyPath:@"bounds.size"] retain];
	theAnimation.duration=0.5;
	theAnimation.delegate = self;
	theAnimation.repeatCount=2;
	theAnimation.autoreverses=YES;
	theAnimation.removedOnCompletion = YES;
	theAnimation.fromValue=zeroNumber;
	theAnimation.toValue=oneNumber;
	theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

	
	
	CABasicAnimation *theAnimation2=[CABasicAnimation animationWithKeyPath:@"position"];
	theAnimation2.duration=0.5;
	theAnimation2.delegate = self;
	theAnimation2.repeatCount=2;
	theAnimation2.autoreverses=YES;
	theAnimation2.removedOnCompletion = YES;
	theAnimation.fromValue=[NSValue valueWithCGPoint:CGPointMake(180, 100)];
	theAnimation2.toValue=[NSValue valueWithCGPoint:CGPointMake(170, 90)];
	
	
	[gameClearLayer addAnimation:theAnimation forKey:@"animateBounds"];
	// [gameClearLayer addAnimation:theAnimation2 forKey:@"animatePosition"];
	*/
	
	/*
	CGPoint point = CGPointMake(180, 100);
	CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    animation.toValue = [NSValue valueWithCGPoint:point];
	animation.delegate = self;
	animation.duration = 0.25;
	animation.autoreverses = TRUE;
	animation.repeatCount = 2;
    [gameClearLayer addAnimation:animation forKey:nil];
    // gameClearLayer.position = point;
	
	
	CGSize size = CGSizeMake(120, 120);
	CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
    NSValue *value = [NSValue valueWithCGSize:size];
    animation2.toValue = value;
	animation2.delegate = self;
	animation2.duration = 0.25;
	animation2.repeatCount = 2;
	animation2.autoreverses = TRUE;
	// animation2.duration = 1;
    [gameClearLayer addAnimation:animation2 forKey:nil];
    // [gameClearLayer setValue:value forKeyPath:@"bounds.size"];
	*/
	
	CABasicAnimation *theAnimation;
	theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
	theAnimation.delegate = self;
	theAnimation.duration = 0.5;
	theAnimation.autoreverses = FALSE;
	theAnimation.fromValue=[NSNumber numberWithFloat:0.0];
	theAnimation.toValue=[NSNumber numberWithFloat:1.0];
	[gameClearLayer addAnimation:theAnimation forKey:nil];
	
	
	/*
	CABasicAnimation *theAnimation;
	theAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
	theAnimation.delegate = self;
	theAnimation.duration = 0.25;
	theAnimation.autoreverses = TRUE;
	theAnimation.repeatCount=5;
	theAnimation.fromValue=[NSNumber numberWithFloat:1.0];
	theAnimation.toValue=[NSNumber numberWithFloat:0.0];
	[self.layer addAnimation:theAnimation forKey:nil];
	*/
	
	// [self setNeedsDisplay];
}

- (void)loadNextLevel:(NSTimer*)theTimer{
	[viewController loadLevel];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	if(_gameClear == TRUE){
		return;
	}
	
	UITouch *aTouch = [touches anyObject];
	CGPoint aPoint = [aTouch locationInView:self];
	NSLog(@"touchBegin at %f,%f", aPoint.x, aPoint.y);
	
	// CGPoint nPoint = [self getFixedHitPoint:aPoint];
	// NSLog(@"picture at %f,%f", nPoint.x, nPoint.y);

	if(aPoint.x > 236.0){
		aPoint.x -= 236.0;
	}
	
	BOOL hitInBlock = FALSE;
	int i;
	for(i=0; i< 5; i++){
		CGRect checkRect = levelBlocks[i];
		if(CGRectEqualToRect(checkRect, CGRectZero)){
			// ignore empty block slot
			continue;
		}
		
		if(CGRectContainsPoint(checkRect, aPoint)){
			NSLog(@"hit in block %f,%f", aPoint.x, aPoint.y);
			
			hitInBlock = TRUE;
			
			// draw quoter
			levelBlockHit[i] = TRUE;
			[self setNeedsDisplay];
			break;
		}
	}
	
	if(! hitInBlock){
		cdCount += CD_COUNT_PUNISH;
	}
	
	int hits = 0;
	for(i=0; i<5; i++){
		if(levelBlockHit[i]){
			hits++;
		}
	}
	
	NSArray *blocks = [levelData valueForKey:@"Blocks"];
	if(hits >= [blocks count]){
		// level complete 
		// send message to controller to next level.
		NSLog(@"level complete");
		[self stopTimer];
		_gameClear = TRUE;
		[self prepareNextLevel];
	}
	
	// check hit in bounds? time punishment
	
	// GameData *gd = [viewController gameData];
	// NSDictionary *level = [gd getLevel];
	// NSLog(@"playuiview gamedata %@", level);
	
}

- (CGPoint)getFixedHitPoint:(CGPoint)p {
	CGPoint retval;
	
	if(p.x > 236.0){
		p.x -= 236.0;
	}
	
	if(p.x >= 8.0 && p.x <= 236.0 && p.y >= 8.0 && p.y <= 236.0){
		retval.x = p.x - 8.0;
		retval.y = p.y - 8.0;
	} else {
		// not in picture
		retval.x = -1.0;
		retval.y = -1.0;
	}
	
	return retval;
}

- (id)initWithFrame:(CGRect)frame viewController:(PlayViewController *)aController levelData:(NSDictionary *)aLevel {
    self = [super initWithFrame:frame];
    if (self != nil) {
        self.viewController = aController;
		
        // set default state
		levelData = [aLevel copy];
        
		int i;
		for(i=0; i<5; i++){
			levelBlocks[i] = CGRectZero;
			levelBlockHit[i] = FALSE;
			
			int isRight = arc4random() % 2;
			levelBlocksRight[i] = ( isRight == 0 ) ? TRUE : FALSE;
		}
		
		cdCount = 0;
		cdCountTotal = CD_COUNT_TOTAL;
		
        _gameOver = FALSE;
		_gameClear = FALSE;
		_gameClearAnimation = FALSE;
		
        // set up sounds and views		
		[self setupSubviewsWithContentFrame:frame];
    }
    return self;
}

-(void)setupSubviewsWithContentFrame:(CGRect)frameRect{
	NSLog(@"contentFrame at (%u,%u) %ux%u", frameRect.origin.x, frameRect.origin.y, frameRect.size.width, frameRect.size.height);

	// background image

	
	
	// progress bar
	CGRect pg2Rect = CGRectMake(8, 246, 464, 10);
	countDownProgressView = [[CountDownProgressView alloc] initWithFrame:pg2Rect];
	countDownProgressView.progress = 1.0;
	[self addSubview:countDownProgressView];

	
	// main pics
	/*
	CGRect picLeftRect = CGRectMake(8, 8, 228, 228);
	CGRect picRightRect = CGRectMake(244, 8, 228, 228);
	*/

	/*
	pic1 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pic_left" ofType:@"png"]];
	NSLog(@"pic1; %ux%u", pic1.size.width, pic1.size.height);
	[pic1 drawInRect:picLeftRect];
	// [pic1 release];

 
	NSString *aqua;
	if(aqua = [[NSBundle mainBundle] pathForResource:@"pic_left" ofType:@"png"] ){
		
		NSLog(@"%s", [aqua UTF8String]);
	}
	 */
	
	//UIImageView *pic1View = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic_left.png"]];
    //pic1View.frame = picLeftRect;
    //pic1View.opaque = YES;
	//[self addSubview:pic1View];
	//[pic1View release];

	/*
	UIImageView *pic2View = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic_left.png"]];
    pic2View.frame = picRightRect;
    pic2View.opaque = YES;
	[self addSubview:pic2View];
	[pic2View release];
	*/
	
	// tools
	
	// buttons
		

	[self startTimer];
	// show me 
	[self setNeedsDisplay];
}


- (void)drawRect:(CGRect)rect {
    // Drawing code
	NSLog(@"drawRect");
	
	int i;
	
	// if(initDraw){
		// NSLog(@"draw quoter");
		// draw block quoter

		
	// } else {
		// NSLog(@"draw init");
		// initDraw = TRUE;
	
	UIImage *bgImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"bg" ofType:@"bmp"]];
	[bgImage drawInRect:rect];
	[bgImage release];
	
	// main pics
	CGRect picLeftRect = CGRectMake(8, 8, 228, 228);
	CGRect picRightRect = CGRectMake(244, 8, 228, 228);
	
	NSString *mainImage = [levelData valueForKey:@"Canvas"];
	NSLog(@"levelData %@", levelData);
	UIImage *pic1 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[mainImage stringByDeletingPathExtension] ofType:[mainImage pathExtension]]];
	// UIImage *pic1 = [[UIImage alloc] imageNamed:@"images/pic_left.png"];
	NSLog(@"mainImage; %f x %f", pic1.size.width, pic1.size.height);
	[pic1 drawInRect:picLeftRect];
	[pic1 drawInRect:picRightRect];
	[pic1 release];

	
	// block pics
	NSArray *blocks = [levelData valueForKey:@"Blocks"];

	

	
	for(i=0; i<[blocks count]; i++){
		NSDictionary *blk = [blocks objectAtIndex:i];
		NSString *tImage = [blk valueForKey:@"image"];
		float x = [[blk valueForKey:@"x"] floatValue];
		float y = [[blk valueForKey:@"y"] floatValue];
		float x2 = x;
		// left or right?
		
		if( levelBlocksRight[i] ){
			x2 += 228.0 + 8.0;
		}
		
		UIImage *pic2 = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[tImage stringByDeletingPathExtension] ofType:[tImage pathExtension]]];
		NSLog(@"Block Image; %f x %f", pic2.size.width, pic2.size.height);
		
		CGRect pic2Rect = CGRectMake(x, y, pic2.size.width, pic2.size.height);
		CGRect pic2Rect2 = CGRectMake(x2, y, pic2.size.width, pic2.size.height);
		
		if(CGRectEqualToRect(levelBlocks[i], CGRectZero)){
			levelBlocks[i] = pic2Rect;
		}
		
		[pic2 drawInRect:pic2Rect2];
		[pic2 release];
	
	}
	
	// NSLog(@"levelBlocks[0] %fx%f", levelBlocks[0].origin.x, levelBlocks[0].origin.y);
	// NSLog(@"levelBlocks[1] %fx%f", levelBlocks[1].origin.x, levelBlocks[1].origin.y);
	// NSLog(@"levelBlocks[2] %fx%f", levelBlocks[2].origin.x, levelBlocks[2].origin.y);
	// NSLog(@"levelBlocks[3] %fx%f", levelBlocks[3].origin.x, levelBlocks[3].origin.y);
	// NSLog(@"levelBlocks[4] %fx%f", levelBlocks[4].origin.x, levelBlocks[4].origin.y);
	
	// }
	
	
	UIImage *pic4q = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"quoter" ofType:@"png"]];
	
	for(i=0; i<5; i++){
		if(levelBlockHit[i]){
			CGRect checkRect = levelBlocks[i];
			CGRect pic4qRect = CGRectMake(checkRect.origin.x - 5, checkRect.origin.y -5, checkRect.size.width + 10, checkRect.size.height + 10);
			CGRect pic4qRect2 = CGRectMake(checkRect.origin.x + 236 - 5, checkRect.origin.y -5, checkRect.size.width + 10, checkRect.size.height + 10);

			[pic4q drawInRect:pic4qRect];
			[pic4q drawInRect:pic4qRect2];
		}
	}
	[pic4q release];	
	
	// countDownProgressView.progress = 0.5;
}


- (void)dealloc {
	[self stopTimer];
	[gameClearLayer release];
	[levelData release];
	[countDownProgressView release];
    [super dealloc];
}


@end
